package com.qffx.moviebase.view;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;

import com.qffx.moviebase.R;
import com.qffx.moviebase.view.impl.BaseActivity;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {
    RecommandFragment recommandFragment = new RecommandFragment();
    ClassifyFragment classifyFragment = new ClassifyFragment();
    FindFragment findFragment = new FindFragment();
    MyFragment myFragment = new MyFragment();
    private List<Fragment> list = new ArrayList<>();
    private FragmentTransaction transaction;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.main_rg);
        radioGroup.setOnCheckedChangeListener(this);
        list.add(recommandFragment);
        list.add(classifyFragment);
        list.add(findFragment);
        list.add(myFragment);
        transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.main_frame, findFragment);
        transaction.commit();
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        switch (id) {
            case R.id.main_recomand:
                showFragment(0);
                break;
            case R.id.main_classify:
                showFragment(1);
                break;
            case R.id.main_find:
                showFragment(2);
                break;
            case R.id.main_my:
                showFragment(3);
                break;


        }


    }

    //展示fragment的方法
    private void showFragment(int position) {
        transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < list.size(); i++) {
            if (i == position) {
                if (!list.get(i).isAdded()) {
                    transaction.add(R.id.main_frame, list.get(i));
                }
                transaction.show(list.get(i));
            } else {
                transaction.hide(list.get(i));
            }
        }
        transaction.commit();
    }

}
